#include "main_interface.h"
#include "ui_main_interface.h"

MainInterface::MainInterface(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainInterface)
{
    ui->setupUi(this);

   this->setWindowTitle("自动重连TCp服务器客户端");


    initializeClient();

    //发送数据到客户端
    connect(ui->pushButton, &QPushButton::clicked,
            this, [&](){
        emit sendData2TcpServer(ui->lineEdit->text().toUtf8());
    });

}

MainInterface::~MainInterface()
{
    //退出客户端
    m_dealTcpClientThreadOne.quit();//停止事件循环
    m_dealTcpClientThreadOne.wait();//阻塞知道线程结束

    delete ui;
}

void MainInterface::initializeClient()
{
    QString ip = "192.168.0.222";
    int port = 10000;

    qDebug()<<"initializeClient()"<< QThread::currentThread();


    //客户端1
    m_tcpClientOne = new TcpClient(this, ip, port);

    m_tcpClientOne->moveToThread(&m_dealTcpClientThreadOne);

    //在主线程中创建
    connect(this, &MainInterface::startClientConnectTcpServer,
            m_tcpClientOne, &TcpClient::initializeFunction);

    //线程销毁
    connect(&m_dealTcpClientThreadOne, &QThread::finished,
            this, &TcpClient::deleteLater);

    //客户端收到的数据
    connect(m_tcpClientOne, &TcpClient::receiveData,
            this, [](QByteArray data){
                qDebug()<<"收到的数据:"<<data;
            });

    //客户端发送数据到服务器
    connect(this, &MainInterface::sendData2TcpServer,
            m_tcpClientOne, &TcpClient::sendData);

    //开启线程
    m_dealTcpClientThreadOne.start();

    //开启客户端重连计时
    emit startClientConnectTcpServer();

}
